package com.edu.hbwe.book.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

/**
 * 处理中文乱码问题
 */
public class EncodingFilter implements Filter {



	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		//处理响应中文乱码问题
		HttpServletResponse resp = (HttpServletResponse) response;
		resp.setContentType("text/html;charset=utf-8");
		
		//处理请求中文乱码问题
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletRequest myRequest = new MyRequest(req);
		chain.doFilter(myRequest, resp);
	}

	
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}
class MyRequest extends HttpServletRequestWrapper{
	
	private HttpServletRequest res;
	private boolean hasEncode;
	
	public MyRequest(HttpServletRequest request) {
		super(request);
		this.res = request;
	}
	
	@Override
	public Map<String, String[]> getParameterMap() {
		// 获取请求方式
		String  method = res.getMethod();
		if(method.equalsIgnoreCase("post")) {
			try {
				res.setCharacterEncoding("UTF-8");
				return res.getParameterMap();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}else if(method.equalsIgnoreCase("get")) {
			Map<String, String[]> parameterMap = res.getParameterMap();
			if(!hasEncode) {
				for (String parameterName : parameterMap.keySet()) {
					String[] values = parameterMap.get(parameterName);
					if(values != null) {
						for(int i=0;i<values.length;i++) {
							String value = values[i];
							try {
								value = new String(value.getBytes("ISO-8859-1"),"UTF-8");
							} catch (UnsupportedEncodingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
					hasEncode = true;
				}
				return parameterMap;
			}
		}
		return super.getParameterMap();
	}
	@Override
	public String getParameter(String name) {
		Map<String, String[]> parameterMap = res.getParameterMap();
		String[] values = parameterMap.get(name);
		if(values == null) {
			return null;
		}
		return values[0];
	}
	@Override
	public String[] getParameterValues(String name) {
		Map<String, String[]> parameterMap = res.getParameterMap();
		String[] values = parameterMap.get(name);
		return values;
	}
}










